package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class AccountServlet
 */
@WebServlet(urlPatterns = { "/Account", "/account", "/AccountServlet",
		"/accountServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public AccountServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<AccountModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				response.sendRedirect("accountNew.jsp");
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			AccountModel query = new AccountModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<AccountModel, AccountModelExt> dal = new GenericDal<AccountModel, AccountModelExt>(
					new AccountModel());

			AccountModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("account", obj);
				getServletContext().getRequestDispatcher("/accountEdit.jsp")
						.forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			AccountModel query = new AccountModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<AccountModel, AccountModelExt> dal = new GenericDal<AccountModel, AccountModelExt>(
					new AccountModel());

			AccountModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("account", obj);
				response.sendRedirect("accountView.jsp");

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			AccountModel obj = new AccountModel();

			// SET NAME here

			GenericDal<AccountModel, AccountModelExt> dal = new GenericDal<AccountModel, AccountModelExt>(
					new AccountModel());
			int res = 0;

			try {
				String strName = request.getParameter("user_name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setUsername(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML(
							"account", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			AccountModel query = new AccountModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<AccountModel, AccountModelExt> dal = new GenericDal<AccountModel, AccountModelExt>(
					new AccountModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("accountList.jsp");
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {

			AccountModel obj = new AccountModel();
			HttpSession session = request.getSession(true);
			String username = request.getParameter("username");
			obj.setUsername(username);

			String password = request.getParameter("password");
			obj.setPassword(password);

			// String status = request.getParameter("status");
			// if (status != null && !status.isEmpty()) {
			// obj.setStatus(Integer.parseInt(status));
			// }

			String email = request.getParameter("email");
			obj.setEmail(email);

			// String type = request.getParameter("type");
			// if (type != null && !type.isEmpty()) {
			// obj.setType(Integer.parseInt(type));
			// }

			// obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<AccountModel, AccountModelExt> dal = new GenericDal<AccountModel, AccountModelExt>(
						new AccountModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res == 0) {
					// TODO : success, refresh cache and redirect to somewhere
					session.setAttribute("username", username);
					session.setAttribute("password", password);
					response.sendRedirect("index.jsp");
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("account", obj);
				getServletContext().getRequestDispatcher("/accountInput.jsp")
						.forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			AccountModel query = new AccountModel();
			String username = request.getParameter("username");
			query.setUsername(username);

			GenericDal<AccountModel, AccountModelExt> dal = new GenericDal<AccountModel, AccountModelExt>(
					new AccountModel());

			AccountModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				String password = request.getParameter("password");
				obj.setPassword(password);

				// String status = request.getParameter("status");
				// if (status != null && !status.isEmpty()) {
				// obj.setStatus(Integer.parseInt(status));
				// }

				String email = request.getParameter("email");
				obj.setEmail(email);

				// String type = request.getParameter("type");
				// if (type != null && !type.isEmpty()) {
				// obj.setType(Integer.parseInt(type));
				// }

				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						response.sendRedirect("accountList.jsp");
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("account", obj);
					getServletContext()
							.getRequestDispatcher("/accountList.jsp").forward(
									request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			AccountModel obj = new AccountModel();

			// SET NAME here

			GenericDal<AccountModel, AccountModelExt> dal = new GenericDal<AccountModel, AccountModelExt>(
					new AccountModel());
			int res = 0;

			try {
				String strName = request.getParameter("username");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setUsername(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML(
							"account", "" + res);
					out.println(resultXML);
				} else {
					// TODO: respone something
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("login")) {

			HttpSession session = request.getSession(true);

			String username = request.getParameter("username");
			String pass = request.getParameter("password");
			session.setAttribute("username", username);
			session.setAttribute("password", pass);

			// System.out.println("---Name, Pass:" + username + ", " + pass);
			/*
			if (username.equals("admin") && pass.equals("admin")) {
				response.sendRedirect("manager.jsp");
				// return;
			} else if (username.equals("user") && pass.equals("user")) {
				response.sendRedirect("index.jsp");
				// return;
			}
			*/
			// else {
			// getServletContext().getRequestDispatcher("/Login.jsp").forward(
			// request, response);
			// }

			int accountType = -1;
			try {
				accountType = AuthenticationUtil.doLogin(request, username,
						pass);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (accountType >= 0) {
				if (accountType == Enums.AccountType.Director.getId()) {
					response.sendRedirect("manager.jsp");
					// return;
				} else {
					response.sendRedirect("index.jsp");
					// return;
				}
			} else {
				getServletContext().getRequestDispatcher("/Login.jsp").forward(
						request, response);
				// return;
			}

			/*
			 * AccountModel query = new AccountModel();
			 * query.setUsername(username); query.setPassword(pass);
			 * 
			 * GenericDal<AccountModel, AccountModelExt> dal = new
			 * GenericDal<AccountModel, AccountModelExt>( new AccountModel());
			 * 
			 * AccountModel obj = null; try { obj = dal.select(query); } catch
			 * (SQLException e) { // TODO Auto-generated catch block
			 * e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO
			 * Auto-generated catch block e.printStackTrace(); } catch
			 * (Exception e) { // TODO Auto-generated catch block
			 * e.printStackTrace(); }
			 * 
			 * if (obj != null) { // TODO : LOAD MASTER DATA HERE // It's
			 * specific code that cannot be generated
			 * 
			 * request.setAttribute("account", obj);
			 * getServletContext().getRequestDispatcher
			 * ("/index.jsp").forward(request, response);
			 * 
			 * } else { // TODO : data not found
			 * getServletContext().getRequestDispatcher
			 * ("/Login.jsp").forward(request, response); }
			 */
		}

	}

}